# BandHot Android构建脚本
# 使用方法: .\android-build.ps1 [build|sign|install|deploy|keygen|check]

param(
    [Parameter(Mandatory=$true)]
    [ValidateSet("build", "build-release", "sign", "install", "deploy", "keygen", "check")]
    [string]$Action
)

# 配置变量 - 请根据你的环境修改这些路径
$ANDROID_SDK_PATH = "D:\Android\SDK"
$BUILD_TOOLS_VERSION = "34.0.0"
$PROJECT_PATH = "D:\VScodeProject\BandHot"
$KEYSTORE_PATH = "$PROJECT_PATH\src-tauri\gen\android\keystore.jks"
$KEY_ALIAS = "bandwidthcontroller"
$STORE_PASS = "123456"
$KEY_PASS = "123456"

# 工具路径
$ADB = "$ANDROID_SDK_PATH\platform-tools\adb.exe"
$APKSIGNER = "$ANDROID_SDK_PATH\build-tools\$BUILD_TOOLS_VERSION\apksigner.bat"

# APK路径
$APK_OUTPUT_DIR = "$PROJECT_PATH\src-tauri\gen\android\app\build\outputs\apk\aarch64\release"
$UNSIGNED_APK = "$APK_OUTPUT_DIR\app-aarch64-release-unsigned.apk"
$SIGNED_APK = "$APK_OUTPUT_DIR\app-signed.apk"

function Write-Info {
    param([string]$Message)
    Write-Host "🔵 $Message" -ForegroundColor Blue
}

function Write-Success {
    param([string]$Message)
    Write-Host "✅ $Message" -ForegroundColor Green
}

function Write-Error {
    param([string]$Message)
    Write-Host "❌ $Message" -ForegroundColor Red
}

function Check-Prerequisites {
    Write-Info "检查构建环境..."
    
    if (!(Test-Path $ANDROID_SDK_PATH)) {
        Write-Error "Android SDK未找到: $ANDROID_SDK_PATH"
        Write-Host "请安装Android Studio或配置ANDROID_SDK_PATH环境变量"
        exit 1
    }
    
    if (!(Test-Path $ADB)) {
        Write-Error "ADB未找到: $ADB"
        exit 1
    }
    
    if (!(Test-Path $APKSIGNER)) {
        Write-Error "APK签名工具未找到: $APKSIGNER"
        Write-Host "请安装Android Build Tools $BUILD_TOOLS_VERSION"
        exit 1
    }
    
    Write-Success "环境检查通过"
}

function Build-Debug {
    Write-Info "构建Debug APK (aarch64)..."
    yarn tauri android build --target aarch64
    if ($LASTEXITCODE -eq 0) {
        Write-Success "Debug APK构建完成"
    } else {
        Write-Error "Debug APK构建失败"
        exit 1
    }
}

function Build-Release {
    Write-Info "构建Release APK (aarch64)..."
    yarn tauri android build --release --target aarch64
    if ($LASTEXITCODE -eq 0) {
        Write-Success "Release APK构建完成"
        Write-Info "未签名APK位置: $UNSIGNED_APK"
    } else {
        Write-Error "Release APK构建失败"
        exit 1
    }
}

function Generate-Keystore {
    Write-Info "生成签名密钥..."
    
    if (Test-Path $KEYSTORE_PATH) {
        $response = Read-Host "密钥文件已存在，是否覆盖? (y/N)"
        if ($response -ne "y" -and $response -ne "Y") {
            Write-Info "跳过密钥生成"
            return
        }
    }
    
    $keystoreDir = Split-Path $KEYSTORE_PATH -Parent
    if (!(Test-Path $keystoreDir)) {
        New-Item -ItemType Directory -Path $keystoreDir -Force
    }
    
    Push-Location $keystoreDir
    keytool -genkey -v -keystore keystore.jks -alias $KEY_ALIAS -keyalg RSA -keysize 2048 -validity 10000
    Pop-Location
    
    if ($LASTEXITCODE -eq 0) {
        Write-Success "签名密钥生成完成: $KEYSTORE_PATH"
    } else {
        Write-Error "签名密钥生成失败"
        exit 1
    }
}

function Sign-APK {
    Write-Info "签名APK..."
    
    if (!(Test-Path $UNSIGNED_APK)) {
        Write-Error "未找到未签名APK: $UNSIGNED_APK"
        Write-Info "请先运行构建: .\android-build.ps1 build-release"
        exit 1
    }
    
    if (!(Test-Path $KEYSTORE_PATH)) {
        Write-Error "未找到签名密钥: $KEYSTORE_PATH"
        Write-Info "请先生成密钥: .\android-build.ps1 keygen"
        exit 1
    }
    
    & $APKSIGNER sign --ks $KEYSTORE_PATH --ks-key-alias $KEY_ALIAS --ks-pass "pass:$STORE_PASS" --key-pass "pass:$KEY_PASS" --out $SIGNED_APK $UNSIGNED_APK
    
    if ($LASTEXITCODE -eq 0) {
        Write-Success "APK签名完成: $SIGNED_APK"
        
        # 验证签名
        & $APKSIGNER verify $SIGNED_APK
        if ($LASTEXITCODE -eq 0) {
            Write-Success "APK签名验证通过"
        }
    } else {
        Write-Error "APK签名失败"
        exit 1
    }
}

function Install-APK {
    Write-Info "安装APK到设备..."
    
    if (!(Test-Path $SIGNED_APK)) {
        Write-Error "未找到已签名APK: $SIGNED_APK"
        Write-Info "请先构建并签名APK"
        exit 1
    }
    
    # 检查设备连接
    $devices = & $ADB devices
    if ($devices -match "device$") {
        Write-Success "发现Android设备"
    } else {
        Write-Error "未发现Android设备"
        Write-Info "请连接设备并启用USB调试"
        exit 1
    }
    
    # 卸载旧版本（如果存在）
    Write-Info "卸载旧版本应用..."
    & $ADB uninstall com.bandwidthcontroller.app 2>$null
    
    # 安装新版本
    & $ADB install $SIGNED_APK
    
    if ($LASTEXITCODE -eq 0) {
        Write-Success "APK安装完成"
        Write-Info "应用已安装到设备，可以在应用列表中找到 'BandHot'"
    } else {
        Write-Error "APK安装失败"
        exit 1
    }
}

function Check-Devices {
    Write-Info "检查连接的Android设备..."
    & $ADB devices -l
    
    $devices = & $ADB devices
    $deviceCount = ($devices | Select-String "device$").Count
    
    if ($deviceCount -gt 0) {
        Write-Success "发现 $deviceCount 个Android设备"
    } else {
        Write-Error "未发现Android设备"
        Write-Info "请连接设备并启用USB调试模式"
    }
}

function Deploy-Full {
    Write-Info "开始完整部署流程..."
    Check-Prerequisites
    Build-Release
    Sign-APK
    Install-APK
    Write-Success "🎉 部署完成！应用已安装到设备"
}

# 主逻辑
switch ($Action) {
    "build" { 
        Check-Prerequisites
        Build-Debug 
    }
    "build-release" { 
        Check-Prerequisites
        Build-Release 
    }
    "sign" { 
        Check-Prerequisites
        Sign-APK 
    }
    "install" { 
        Check-Prerequisites
        Install-APK 
    }
    "deploy" { 
        Deploy-Full 
    }
    "keygen" { 
        Generate-Keystore 
    }
    "check" { 
        Check-Devices 
    }
}

Write-Host "`n🔧 使用帮助:" -ForegroundColor Yellow
Write-Host "  构建Debug版本:     .\android-build.ps1 build" -ForegroundColor Gray
Write-Host "  构建Release版本:    .\android-build.ps1 build-release" -ForegroundColor Gray
Write-Host "  生成签名密钥:       .\android-build.ps1 keygen" -ForegroundColor Gray
Write-Host "  签名APK:           .\android-build.ps1 sign" -ForegroundColor Gray
Write-Host "  安装到设备:         .\android-build.ps1 install" -ForegroundColor Gray
Write-Host "  完整部署流程:       .\android-build.ps1 deploy" -ForegroundColor Gray
Write-Host "  检查设备连接:       .\android-build.ps1 check" -ForegroundColor Gray 